<template> 
  <div>
    <el-upload
      :class="{'upload-card':value}"
      :action="uploadFileUrl"
      :data="dataObj"
      :multiple="false"
      :list-type="prefixDir==='image'?'picture-card':'text'"
      :show-file-list="showFileList"
      :file-list="fileList"
      :accept="fileType.join(',')"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <i class="el-icon-plus" v-if="prefixDir==='image'&&!value"></i>
      <el-button v-if="prefixDir!='image'" size="small" type="primary" :loading="uploadLoading">点击上传</el-button>
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
        <template v-if="fileSize">大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b></template>
        <template v-if="fileType">，格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
        的文件
      </div>
    </el-upload>
    <el-dialog title="上传文件详情" :visible.sync="dialogVisible" append-to-body>
      <img v-if="prefixDir==='image'" width="100%" :src="fileList[0].url" alt=""/>
      <audio v-if="prefixDir==='music'" width="100%" autoplay controls :src="fileList[0].url"/>
    </el-dialog>
  </div>
</template>
<script>
import fileUpload from '@/utils/upload'
import {deleteOss, policy} from '@/api/oss/index'

export default {
  name: 'singleUpload',
  props: {
    value: String,
    //路径前缀
    prefixDir: {
      type: String,
      default: 'image'
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['.png', '.jpg', '.jpeg']
    fileType: {
      type: Array,
      default: () => ['.png', '.jpg', '.jpeg'],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize) && !this.value;
    },
    imageUrl() {
      return this.value;
    },
    imageName() {
      if (this.value != null && this.value !== '') {
        return this.value.substr(this.value.lastIndexOf("/") + 1);
      } else {
        return null;
      }
    },
    fileList() {
      return [{
        name: this.imageName,
        url: this.imageUrl
      }]
    },
    showFileList: {
      get: function () {
        return this.value !== null && this.value !== '' && this.value !== undefined;
      },
      set: function (newValue) {
      }
    }
  },
  data() {
    return {
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: '',
      },
      uploadFileUrl: fileUpload.baseUrl,
      uploadLoading: false,
      dialogVisible: false,
    };
  },
  methods: {
    emitInput(val) {
      this.$emit('input', val)
    },
    handleRemove(file, fileList) {
      deleteOss({fileKey: this.dataObj.key}).then(response => {
        if (response.code === 200) {
          this.emitInput('');
        } else {
          this.$modal.msgError(response.msg);
        }
      })
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      let _self = this;
      _self.uploadLoading = true;
      return new Promise((resolve, reject) => {
        policy({dirType: _self.prefixDir}).then(response => {
          _self.dataObj.policy = response.data.policy;
          _self.dataObj.signature = response.data.signature;
          _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
          _self.dataObj.key = response.data.dir + '/' + file.name;
          _self.dataObj.dir = response.data.dir;
          _self.dataObj.host = response.data.host;
          resolve(true)
        }).catch(err => {
          _self.uploadLoading = false;
          console.log("上传：" + err)
          reject(false)
        })
      })
    },
    handleUploadSuccess(res, file) {
      this.showFileList = true;
      this.uploadLoading = false;
      this.fileList.pop();
      this.fileList.push({
        name: file.name,
        url: this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name
      });
      this.emitInput(this.fileList[0].url);
    }
  }
}
</script>
<style scoped>
.upload-card >>> .el-upload--picture-card {
  display: none;
}
</style>


